package com.boang.dao;

import com.boang.po.Cla;
import com.boang.po.Page;
import com.boang.po.Student;
import com.boang.util.DBUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/*
  @author: 13813
  @date: 2024/7/15 10:01
*/
public class ClaDaoImpl implements ClaDao {
    @Override
    public Page<Cla> selectClaList(int pageNum, int pageSize) {
        Connection conn = null;
        try {
            conn = DBUtil.getConn();
            PreparedStatement preparedStatement = conn.prepareStatement("select * from cla order by id desc limit ?,?");
            preparedStatement.setInt(1, (pageNum - 1) * pageSize);
            preparedStatement.setInt(2, pageSize);
            ResultSet resultSet = preparedStatement.executeQuery();
            ArrayList<Cla> list = new ArrayList<Cla>();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int num = resultSet.getInt("num");
                Cla cla = new Cla(id, name, num);
                list.add(cla);
            }

            //总条数
            PreparedStatement preparedStatement2 = conn.prepareStatement("select count(*) from cla");
            ResultSet resultSet2 = preparedStatement2.executeQuery();
            int total = 0;
            while (resultSet2.next()) {
                total = resultSet2.getInt(1);
            }
            int pages = 0;
            if (total % pageSize == 0) {
                pages = total / pageSize;
            } else {
                pages = (total / pageSize) + 1;
            }
            return new Page<Cla>(pageNum, pageSize, pages, total, list);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insertCla(Cla cla) {
        try {
            Connection conn = DBUtil.getConn();
            PreparedStatement preparedStatement = conn.prepareStatement("insert into cla(name,num)values(?,?)");
            preparedStatement.setString(1, cla.getName());
            preparedStatement.setInt(2, cla.getNum());
            int i = preparedStatement.executeUpdate();
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
